package com.ve.c51;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ve.clexer.LexerSpannerAdapter;
import com.ve.compiler.Compiler;
import com.ve.compiler.ExampleInstaller;
import com.ve.compiler.ProgressListener;
import com.ve.ext.AutoCompleteLayout;
import com.ve.file.FileAdapter;
import com.ve.file.GFile;
import com.ve.file.ItemListener;
import com.ve.view.editor.Editor;
import com.ve.view.editor.out.Config;
import com.ve.view.ext.SelectActionLayout;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private Editor editor;
    private SelectActionLayout selectActionLayout;
    private Toolbar toolbar;
    private FileAdapter fileAdapter;
    private RecyclerView fileList;
    private DrawerLayout drawerLayout;
    private GFile currentFile;
    private AutoCompleteLayout autoCompleteLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initFileList();

        initToolbar();
        initDrawer();
        initEditor();

        autoCompleteLayout=new AutoCompleteLayout(editor);
        open(new GFile(ExampleInstaller.getDir() + "/test.c"));

    }

    private void initDrawer() {
        drawerLayout = findViewById(R.id.activity_main_drawer);
        drawerLayout.addDrawerListener(new android.support.v4.app.ActionBarDrawerToggle(this, drawerLayout, true, R.drawable.ic_undo, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                fileAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initEditor() {
        editor = findViewById(R.id.activity_main_editor);

        Config config = new Config();
        config.showNonPrinting = true;
        config.wordWrap = false;
        editor.applyConfig(config);
        selectActionLayout = new SelectActionLayout(editor);
        editor.getSpanInterface().setTextSpanner(new LexerSpannerAdapter());
        editor.getOperator().setSelectionChangedListener((active, selStart, selEnd) -> {
            if (active) {
                selectActionLayout.show();
            } else {
                selectActionLayout.hide();
            }
        });
    }

    private void initToolbar() {
        toolbar = findViewById(R.id.activity_main_toolbar);
        setSupportActionBar(toolbar);
    }

    private void initFileList() {
        fileList = findViewById(R.id.activity_main_file_list);

        fileAdapter = new FileAdapter();
        fileAdapter.addChild(new GFile(ExampleInstaller.getDir().getAbsolutePath()));
        fileAdapter.addChild(new GFile("/sdcard"));
        fileList.setAdapter(fileAdapter);
        fileList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
        fileList.setLayoutManager(new LinearLayoutManager(this));
        fileAdapter.setItemListener(new ItemListener() {
            @Override
            public void onOpen(int index, GFile file) {
                open(file);
                drawerLayout.closeDrawer(Gravity.START);
            }

            @Override
            public void onLongClick(View view, int index, GFile file) {
                if (file.isDirectory()){
                    createNew(file.getPath());
                    fileAdapter.reset();
                }
            }
        });
    }
    private void createNew(String path) {
        final EditText editText = new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("新建文件").setView(editText);
        inputDialog.setPositiveButton("确定", (dialog, which) -> {
            String string = editText.getText().toString();
            File file = new File(new File(path), string);
            if (file.exists()) {
                Toast.makeText(MainActivity.this, "文件已经存在", Toast.LENGTH_SHORT).show();
            }else {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                open(new GFile(file.getAbsolutePath()));
                dialog.dismiss();
            }
        }).show();
    }
    private void open(GFile file) {
        if (!new File(file.getPath()).exists()) {

            return;
        }
        currentFile = file;
        try {
            String string = IOUtils.toString(new FileInputStream(currentFile.getPath()), Charset.defaultCharset());
            editor.getTextInterface().setText(string);
        } catch (IOException e) {
            Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }


    private void save() {
        try {
            IOUtils.write(editor.getTextInterface().getText(), new FileOutputStream(currentFile.getPath()));
            fileAdapter.reset();
        } catch (IOException e) {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    public void compile() {
        save();
        Compiler compiler = Compiler.getCompiler();
        compiler.setProgressListener(new ProgressListener.DialogProgressAdapter(this, "编译") {
            @Override
            public void onSucceed(String info) {
                super.onSucceed(info);
                Toast.makeText(MainActivity.this, "编译完成", Toast.LENGTH_SHORT).show();
                fileAdapter.reset();
            }
        });

        compiler.compile(this, new File(currentFile.getPath()));
    }

    public void download() {
        if (Compiler.isMakeFile(new File(currentFile.getPath()))){
            DownloadActivity.start(MainActivity.this, "");
            return;
        }
        save();
        ProgressListener.DialogProgressAdapter progressListener = new ProgressListener.DialogProgressAdapter(this, "编译") {
            @Override
            public void onSucceed(String info) {
                super.dismissDialog();
                fileAdapter.reset();
                DownloadActivity.start(MainActivity.this, info);
            }
        };
        Compiler.getCompiler().setProgressListener(progressListener);
        Compiler.getCompiler().compile(this, new File(currentFile.getPath()));

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_toolbar, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.undo:
                editor.getTextInterface().undo();
                break;
            case R.id.redo:
                editor.getTextInterface().redo();
                break;
            case R.id.compile:
                compile();
                break;
            case R.id.download:
                download();
                break;
            case R.id.console:
                startActivity(new Intent(this,ConsoleActivity.class));
                break;

        }
        return super.onOptionsItemSelected(item);
    }


}
